import $ from "jquery";
import { ITodoData } from "./typings";

export function getTodoList(
  target: any,
  methodName: string,
  descriptor: PropertyDescriptor
): void {
  const _origin = descriptor.value;
  descriptor.value = async function (todoData: ITodoData[]) {
    const ret: string = await $.get("http://localhost:8080/todolist");
    if (!ret) return;
    todoData = JSON.parse(ret);
    _origin.call(this, todoData);
  };
}

export function removeTodo(
  target: any,
  methodName: string,
  descriptor: PropertyDescriptor
): void {
  const _origin = descriptor.value;
  descriptor.value = async function (target: HTMLElement, id: number) {
    const ret: string = await $.post("http://localhost:8080/remove", { id });
    _origin.call(this, target, id);
  };
}

export function addTodo(
  target: any,
  methodName: string,
  descriptor: PropertyDescriptor
): void {
  const _origin = descriptor.value;
  descriptor.value = async function (todo: ITodoData) {
    const { msg, code } = await $.post("http://localhost:8080/add", { todo: JSON.stringify(todo) });
    if (code === 100) return alert(msg);
    _origin.call(this, todo);
  };
}
export function taogleTodo(
  target: any,
  methodName: string,
  descriptor: PropertyDescriptor
): void {
  const _origin = descriptor.value;
  descriptor.value = async function (target: HTMLElement, id: number) {
    const ret: string = await $.post("http://localhost:8080/toggle", { id });
    _origin.call(this, target, id);
  };
}
